<?php

declare(strict_types=1);

namespace app\controller\system;

use app\BaseController;
use app\model\User;
use app\service\factory\ResponseFactory;
use app\service\sys\AccountService;
use app\validate\system\SysAccountValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Account extends BaseController
{
    public function index(AccountService $accountService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'keyword',
                'status',
                'role_id',
            ], 'get');

            $paginator = $accountService->paginate($filters, $page, $pageSize);
            $list = $accountService->formatCollection($paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, AccountService $accountService): Response
    {
        try {
            $user = $accountService->findById($id);
            if (!$user) {
                return json(ResponseFactory::error('用户不存在', 404));
            }

            return json(ResponseFactory::success($accountService->format($user)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(AccountService $accountService): Response
    {
        try {
            $payload = $this->request->only([
                'phone',
                'email',
                'password',
                'status',
                'nickname',
                'real_name',
                'role_ids',
            ], 'post');

            $this->validate($payload, SysAccountValidate::class . '.create');

            $user = $accountService->create($payload);

            return json(ResponseFactory::success($accountService->format($user), '账户已创建'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(int $id, AccountService $accountService): Response
    {
        try {
            $user = $accountService->findById($id);
            if (!$user) {
                return json(ResponseFactory::error('用户不存在', 404));
            }

            $payload = $this->request->only([
                'phone',
                'email',
                'password',
                'status',
                'nickname',
                'real_name',
                'role_ids',
            ], 'put');
            $payload['id'] = $id;

            $this->validate($payload, SysAccountValidate::class . '.update');

            $updated = $accountService->update($user, $payload);

            return json(ResponseFactory::success($accountService->format($updated), '账户已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function delete(int $id, AccountService $accountService): Response
    {
        try {
            $user = User::find($id);
            if (!$user) {
                return json(ResponseFactory::error('用户不存在', 404));
            }

            if (!$accountService->delete($user)) {
                return json(ResponseFactory::error('删除失败', 500));
            }

            return json(ResponseFactory::success(true, '账户已删除'));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
